<div class="row">
    <div class="col-md-12">
        <!-- 搜索筛选区域 -->
        <div class="card">
            <div class="card-body">
                <form method="GET" action="{{ route('dcat.admin.admin.pickup.index') }}">
                    <div class="row mb-3">
                        <!-- 第一行：省市区和自提点名称 -->
                        <div class="col-md-2">
                            <label class="form-label">省</label>
                            <select class="form-control" id="province" name="province">
                                <option value="">选择省</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">市</label>
                            <select class="form-control" id="city" name="city" disabled>
                                <option value="">选择市</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">区县</label>
                            <select class="form-control" id="district" name="district" disabled>
                                <option value="">选择区县</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">自提点名称</label>
                            <input type="text" class="form-control" id="pickup_name" name="pickup_name" placeholder="请输入自提点名称" value="{{ request('pickup_name') }}">
                        </div>
                        <div class="col-md-4 d-flex align-items-end">
                            <div class="d-flex">
                                <button type="submit" class="btn btn-primary btn-sm mr-1">
                                    <i class="fa fa-search"></i> 查询
                                </button>
                                <a href="{{ route('dcat.admin.admin.pickup.index') }}" class="btn btn-secondary btn-sm">
                                    <i class="fa fa-refresh"></i> 重置
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <!-- 第二行：申请人相关字段 -->
                        <div class="col-md-2">
                            <label class="form-label">申请人ID</label>
                            <input type="text" class="form-control" id="applicant_id" name="applicant_id" placeholder="申请人ID" value="{{ request('applicant_id') }}">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">会员昵称/手机号</label>
                            <input type="text" class="form-control" id="member_info" name="member_info" placeholder="会员昵称或手机号" value="{{ request('member_info') }}">
                        </div>
                        <div class="col-md-6">
                            <!-- 预留空间，保持布局对齐 -->
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- 自提点列表 -->
        <div class="card mt-3">
            <div class="card-body p-0">

                <!-- 数据表格 -->
                <div class="table-responsive">
                    <table class="table table-hover table-striped mb-0">
                        <thead class="bg-light">
                            <tr>
                                <th style="width: 140px;">自提点ID</th>
                                <th style="width: 200px;">自提点名称</th>
                                <th style="width: 160px;">所在区县</th>
                                <th style="width: 180px;">申请人信息</th>
                                <th style="width: 150px;">申请人手机号</th>
                                <th style="width: 80px;">状态</th>
                                <th style="width: 240px;">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($pickupPoints as $point)
                            <tr>
                                <td><strong>{{ $point['id'] }}</strong></td>
                                <td>{{ $point['name'] }}</td>
                                <td>
                                    <span class="text-primary">{{ $point['district'] }}</span>
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="avatar avatar-sm rounded-circle mr-2">
                                            <img src="{{ $point['applicant']['avatar'] }}" alt="{{ $point['applicant']['name'] }}" class="rounded-circle" style="width: 32px; height: 32px;">
                                        </div>
                                        <div>
                                            <div><strong>{{ $point['applicant']['name'] }}</strong></div>
                                            <small class="text-muted">ID: {{ $point['applicant']['id'] }}</small>
                                        </div>
                                    </div>
                                </td>
                                <td>{{ $point['phone'] }}</td>
                                <td>
                                    @if($point['pickup_point_status'] == 'allow')
                                        <span class="badge badge-success">{{ $point['status'] }}</span>
                                    @else
                                        <span class="badge badge-danger">{{ $point['status'] }}</span>
                                    @endif
                                </td>
                                <td>
                                    @if($point['pickup_point_status'] == 'allow')
                                        <a href="#" class="text-danger mr-2" onclick="togglePickupStatus({{ $point['id'] }}, 'deny')">停用</a>
                                    @else
                                        <a href="#" class="text-success mr-2" onclick="togglePickupStatus({{ $point['id'] }}, 'allow')">启用</a>
                                    @endif
                                    <a href="#" class="text-info mr-2" data-pickup-id="{{ $point['id'] }}" onclick="showDetailModal(this.dataset.pickupId)">详情</a>
                                    <a href="/admin/suppliers?store_id={{ $point['id'] }}" class="text-warning" title="查看该自提点支持的供应商">支持的供应商</a>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                
                <!-- 底部统计和分页 -->
                <div class="d-flex justify-content-between align-items-center p-3 bg-light">
                    <div class="text-muted">
                        共 {{ $stores->total() }} 条记录
                    </div>
                    <nav aria-label="自提点分页">
                        @if($stores->hasPages())
                            {{ $stores->appends(request()->query())->links() }}
                        @endif
                    </nav>
                </div>
        </div>
    </div>
</div>

<!-- 自提点详情弹窗 -->
<div class="modal fade" id="pickupDetailModal" tabindex="-1" role="dialog" aria-labelledby="pickupDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="pickupDetailModalLabel">
                    <i class="fa fa-store"></i> 自提点详情
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="pickupDetailContent">
                <div class="text-center py-5">
                    <i class="fa fa-spinner fa-spin fa-2x text-muted"></i>
                    <p class="text-muted mt-2">加载中...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.avatar {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
}

.form-label {
    font-weight: 500;
    margin-bottom: 5px;
    color: #495057;
    font-size: 13px;
}

/* 紧凑的查询区域样式 */
.card-body .row.mb-3 {
    margin-bottom: 1rem !important;
}

.card-body .form-control {
    font-size: 13px;
    padding: 0.375rem 0.5rem;
}

.btn-sm {
    font-size: 12px;
    padding: 0.25rem 0.5rem;
}

.table th {
    border-top: none;
    font-weight: 600;
    color: #495057;
    background-color: #f8f9fa !important;
}

.table td {
    vertical-align: middle;
    padding: 12px 8px;
}

.badge {
    font-size: 11px;
    padding: 4px 8px;
}

.text-primary:hover,
.text-info:hover,
.text-warning:hover {
    text-decoration: underline;
}

.modal-xl {
    max-width: 1200px;
}


</style>

<script>
function showDetailModal(pickupId) {
    // 显示弹窗
    $('#pickupDetailModal').modal('show');
    
    // 重置内容为加载状态
    $('#pickupDetailContent').html(`
        <div class="text-center py-5">
            <i class="fa fa-spinner fa-spin fa-2x text-muted"></i>
            <p class="text-muted mt-2">加载中...</p>
        </div>
    `);
    
    // 发送Ajax请求获取详情数据
    $.ajax({
        url: `/admin/pickup/${pickupId}`,
        type: 'GET',
        success: function(response) {
            $('#pickupDetailContent').html(response);
        },
        error: function(xhr, status, error) {
            $('#pickupDetailContent').html(`
                <div class="text-center py-5">
                    <i class="fa fa-exclamation-triangle fa-2x text-danger"></i>
                    <p class="text-danger mt-2">加载失败，请稍后重试</p>
                    <button class="btn btn-secondary" onclick="showDetailModal(${pickupId})">重新加载</button>
                </div>
            `);
        }
    });
}

// 切换自提点状态
function togglePickupStatus(storeId, newStatus) {
    var statusText = newStatus === 'allow' ? '启用' : '停用';
    var confirmMessage = `确定要${statusText}该自提点吗？`;
    
    if (typeof Dcat !== 'undefined' && Dcat.confirm) {
        Dcat.confirm('确认操作', confirmMessage, function() {
            updatePickupStatus(storeId, newStatus);
        });
    } else if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: '确认操作',
            text: confirmMessage,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: newStatus === 'allow' ? '#28a745' : '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: `确定${statusText}`,
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                updatePickupStatus(storeId, newStatus);
            }
        });
    } else {
        if (confirm(confirmMessage)) {
            updatePickupStatus(storeId, newStatus);
        }
    }
}

// 更新自提点状态
function updatePickupStatus(storeId, newStatus) {
    $.ajax({
        url: `/admin/api/pickup/toggle-status`,
        type: 'POST',
        data: {
            store_id: storeId,
            pickup_point_status: newStatus,
            _token: $('meta[name="csrf-token"]').attr('content')
        },
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                showMessage(response.message, 'success');
                // 刷新页面或更新状态显示
                location.reload();
            } else {
                showMessage('操作失败：' + response.message, 'error');
            }
        },
        error: function(xhr, status, error) {
            console.error('状态切换失败:', error);
            showMessage('操作失败，请重试', 'error');
        }
    });
}

// 显示消息提示
function showMessage(message, type = 'info') {
    if (typeof Dcat !== 'undefined') {
        if (type === 'success') {
            Dcat.success(message);
        } else if (type === 'error') {
            Dcat.error(message);
        } else {
            Dcat.info(message);
        }
    } else if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: type === 'success' ? '成功' : type === 'error' ? '错误' : '提示',
            text: message,
            icon: type,
            confirmButtonText: '确定'
        });
    } else {
        alert(message);
    }
}



// 省市区三级联动
$(document).ready(function() {
    // 初始化工具提示
    $('[data-toggle="tooltip"]').tooltip();
    
    // 页面加载时获取省份列表
    loadProvinces();
    
    // 省份选择变化事件
    $('#province').change(function() {
        var provinceId = $(this).val();
        resetCityAndDistrict();
        
        if (provinceId) {
            loadCities(provinceId);
            $('#city').prop('disabled', false);
        } else {
            $('#city').prop('disabled', true);
        }
    });
    
    // 城市选择变化事件
    $('#city').change(function() {
        var cityId = $(this).val();
        resetDistrict();
        
        if (cityId) {
            loadDistricts(cityId);
            $('#district').prop('disabled', false);
        } else {
            $('#district').prop('disabled', true);
        }
    });
    
    // 获取省份列表
    function loadProvinces() {
        $.ajax({
            url: '{{ route("dcat.admin.admin.api.address.provinces") }}',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    var provinceSelect = $('#province');
                    provinceSelect.empty().append('<option value="">选择省</option>');
                    
                    $.each(response.data, function(index, province) {
                        var selected = '{{ request("province") }}' == province.id ? 'selected' : '';
                        provinceSelect.append('<option value="' + province.id + '" ' + selected + '>' + province.name + '</option>');
                    });
                    
                    // 如果有预选值，触发城市加载
                    var selectedProvince = '{{ request("province") }}';
                    if (selectedProvince) {
                        loadCities(selectedProvince, '{{ request("city") }}');
                        $('#city').prop('disabled', false);
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('获取省份列表失败:', error);
                showToast('获取省份列表失败，请刷新页面重试', 'error');
            }
        });
    }
    
    // 获取城市列表
    function loadCities(provinceId, selectedCityId = '') {
        $.ajax({
            url: '{{ route("dcat.admin.admin.api.address.cities", ":provinceId") }}'.replace(':provinceId', provinceId),
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    var citySelect = $('#city');
                    citySelect.empty().append('<option value="">选择市</option>');
                    
                    $.each(response.data, function(index, city) {
                        var selected = selectedCityId == city.id ? 'selected' : '';
                        citySelect.append('<option value="' + city.id + '" ' + selected + '>' + city.name + '</option>');
                    });
                    
                    // 如果有预选值，触发区县加载
                    if (selectedCityId) {
                        loadDistricts(selectedCityId, '{{ request("district") }}');
                        $('#district').prop('disabled', false);
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('获取城市列表失败:', error);
                showToast('获取城市列表失败，请重试', 'error');
            }
        });
    }
    
    // 获取区县列表
    function loadDistricts(cityId, selectedDistrictId = '') {
        $.ajax({
            url: '{{ route("dcat.admin.admin.api.address.districts", ":cityId") }}'.replace(':cityId', cityId),
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    var districtSelect = $('#district');
                    districtSelect.empty().append('<option value="">选择区县</option>');
                    
                    $.each(response.data, function(index, district) {
                        var selected = selectedDistrictId == district.id ? 'selected' : '';
                        districtSelect.append('<option value="' + district.id + '" ' + selected + '>' + district.name + '</option>');
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error('获取区县列表失败:', error);
                showToast('获取区县列表失败，请重试', 'error');
            }
        });
    }
    
    // 重置城市和区县下拉框
    function resetCityAndDistrict() {
        $('#city').empty().append('<option value="">选择市</option>').prop('disabled', true);
        $('#district').empty().append('<option value="">选择区县</option>').prop('disabled', true);
    }
    
    // 重置区县下拉框
    function resetDistrict() {
        $('#district').empty().append('<option value="">选择区县</option>').prop('disabled', true);
    }
    
    // 显示提示信息
    function showToast(message, type = 'info') {
        // 简单的提示实现，可以根据项目需求调整
        if (typeof Dcat !== 'undefined' && Dcat.success) {
            if (type === 'success') {
                Dcat.success(message);
            } else if (type === 'error') {
                Dcat.error(message);
            } else {
                Dcat.info(message);
            }
        } else {
            alert(message);
        }
    }
});
</script>